package com.skwyb.form.controller.system;

import com.skwyb.form.constants.ResultCode;
import com.skwyb.form.core.BusinessException;
import com.skwyb.form.core.ObjectResult;
import com.skwyb.form.utils.DateUtil;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@Log4j2
@RestController
@RequestMapping("/admin/file")
public class FileUploadController {

    @Value("${file.imgSuffixName}")
    private String imgSuffixName;

    @Value("${file.storageDir}")
    private String storageDir;

    @PostMapping("/uploadImg")
    public ObjectResult upload(@RequestParam("file") MultipartFile[] file) throws BusinessException {
        //创建目录
        String[] dir = createDir();

        List<String> files = new ArrayList<>();
        for (int i = 0; i < file.length; i++) {
            MultipartFile tFile = file[i];
            if (tFile.isEmpty()) {
                log.error("上传第" + (i++) + "个文件失败");
                continue;
            }

            String fileName = tFile.getOriginalFilename();
            String suffix = checkFileSuffixName(fileName);
            fileName = UUID.randomUUID().toString().replace("-", "") + suffix;

            try {
                File dest = new File(dir[1] + File.separator + fileName);
                tFile.transferTo(dest);
                log.info("第" + (i + 1) + "个文件上传成功");
                files.add(dir[0] + fileName);
            } catch (IOException e) {
                log.error("上传第" + (i++) + "个文件失败", e);
                throw new BusinessException(ResultCode.FILE_UPLOAD_ERROR);
            }
        }
        return new ObjectResult(files);
    }

    private String[] createDir() throws BusinessException {
        try {
            //获取跟目录
            String year = DateUtil.getDate("yyyy");
            String month = DateUtil.getDate("MM");
            String dirPath = "attachment" + File.separator + year + File.separator + month + File.separator;
            File fileDir = new File(storageDir, dirPath);
            if (!fileDir.exists()) {
                fileDir.mkdirs();
            }
            String[] a = new String[2];
            a[0] = dirPath;
            a[1] = fileDir.getCanonicalPath();
            return a;
        } catch (IOException e) {
            log.error("创建目录失败", e);
            throw new BusinessException(ResultCode.FILE_UPLOAD_ERROR);
        }

    }

    /**
     * 检查文件后缀名
     */
    private String checkFileSuffixName(String fileName) throws BusinessException {
        if (StringUtils.isBlank(fileName)) {
            throw new BusinessException(ResultCode.FILE_FORMAT_ERROR);
        }

        //获取文件后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));

        String[] str = imgSuffixName.split("\\|");
        for (String i : str) {
            if (i.equals(suffixName)) {
                return suffixName;
            }
        }
        throw new BusinessException(ResultCode.FILE_FORMAT_ERROR);
    }
}
